import { fabric } from 'fabric';

class Square extends fabric.Rect {
  constructor(options = {}) {
    const defaultOptions = {
      left: 100,
      top: 100,
      width: 100,
      height: 100,
      fill: '#ffffff',
      strokeWidth: 1,
      stroke: '#000000',
      selectable: true,
      cornerSize: 10,
      transparentCorners: false,
      hasRotatingPoint: true,
      padding: 5,
      lockAspectRatio: true, // 锁定宽高比
      id: '',  // 添加id属性
    };

    // 合并默认选项和传入的选项
    const mergedOptions = {
      ...defaultOptions,
      ...options,
      // 确保高度等于宽度
      height: options.width || defaultOptions.width,
    };

    // 确保控制点颜色与边框颜色一致
    mergedOptions.cornerColor = mergedOptions.stroke;
    mergedOptions.borderColor = mergedOptions.stroke;

    // 调用父类构造函数
    super(mergedOptions);

    // 监听缩放事件，确保保持正方形
    this.on('scaling', this._maintainSquareShape.bind(this));
  }

  // 确保在缩放时保持正方形形状
  _maintainSquareShape(event) {
    const target = event.target;
    if (target.scaleX !== target.scaleY) {
      // 使用较大的缩放值
      const maxScale = Math.max(target.scaleX, target.scaleY);
      target.set({
        scaleX: maxScale,
        scaleY: maxScale,
      });
    }
  }

  // 更新属性
  updateProps(props) {
    // 如果更新宽度，同时更新高度
    if (props.width) {
      props.height = props.width;
    }
    this.set(props);
    // 如果更新了边框颜色，同时更新控制点颜色
    if (props.stroke) {
      this.set({
        cornerColor: props.stroke,
        borderColor: props.stroke,
      });
    }
    this.canvas?.requestRenderAll();
    return this;
  }

  // 移到顶层
  bringToFront() {
    if (this.canvas) {
      this.canvas.bringToFront(this);
      this.canvas.requestRenderAll();
    }
    return this;
  }

  // 移到底层
  sendToBack() {
    if (this.canvas) {
      this.canvas.sendToBack(this);
      this.canvas.requestRenderAll();
    }
    return this;
  }

  // 删除自身
  remove() {
    if (this.canvas) {
      this.canvas.remove(this);
      this.canvas.requestRenderAll();
    }
  }

  // 设置大小
  setSize(size) {
    this.set({
      width: size,
      height: size,
      scaleX: 1,
      scaleY: 1,
    });
    this.canvas?.requestRenderAll();
    return this;
  }
}

export default Square;
